package com.bitcola.security.activity.biz;


import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.bitcola.security.activity.entity.Charity;
import com.bitcola.security.activity.entity.CharityLog;
import com.bitcola.security.activity.entity.CharityRow;
import com.bitcola.security.activity.mapper.CharityLogMapper;
import com.bitcola.security.activity.mapper.CharityMapper;
import com.bitcola.security.activity.mapper.CharityRowMapper;

import com.bitcola.security.common.exception.RepeatException;
import com.bitcola.security.common.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service

public class CharityBiz {
    @Autowired
    CharityMapper charityMapper;
    @Autowired
    CharityRowMapper charityRowMapper;

    @Autowired
    CharityLogMapper charityLogMapper;

    Snowflake snowflake=new Snowflake(1,2);

    @Cached(cacheType=CacheType.LOCAL,expire = 60)
    public Charity getCurrent()
    {
        return charityMapper.selectAll().get(0);
    }

    public List<CharityRow>getRow(String  userId,int num)
    {
        Example example=new Example(CharityRow.class);
        example.createCriteria().andEqualTo("count",num);
        var result= charityRowMapper.selectByExample(example);
        Example logExample=new Example(CharityLog.class);
        if(StringUtils.isNotEmpty(userId)){
            logExample.createCriteria().andEqualTo("userId",userId).andEqualTo("num",num);
           var log=    charityLogMapper.selectByExample(logExample);
           if(log!=null) {
               for (CharityRow charityRow : result) {

                   for(CharityLog charityLog:log) {
                       if (charityRow.getId().equals(charityLog.getRowId())) {
                           charityRow.setLiked(true);
                       }
                   }
               }
           }
        }
        return result;

    }


    public int support(String userId,String rowId)
    {
        Example logExample=new Example(CharityLog.class);
        logExample.createCriteria().andEqualTo("userId",userId).andEqualTo("rowId",rowId);
        int count=charityLogMapper.selectCountByExample(logExample);
        if(count==0){
            var row= charityRowMapper.selectByPrimaryKey(rowId);
            int num=row.getSupports()+1;
            row.setSupports(num);
            charityRowMapper.updateByPrimaryKey(row);
            CharityLog log=new CharityLog();
            log.setId(snowflake.nextIdStr());
            log.setNum(row.getCount());
            log.setRowId(rowId);
            log.setUserId(userId);
            charityLogMapper.insert(log);
            return num;
        }

        throw new RepeatException("已经点赞过了");

    }



}
